package com.miku.blog.service.impl;

import com.miku.blog.domain.pojo.ResponseResult;
import com.miku.blog.domain.pojo.SystemConstance;
import com.miku.blog.service.ArticleViewService;
import com.miku.blog.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.UUID;

/**
 * @author shkstart
 * @create ${}YEAR-06-18 5:24
 */
@Service
public class ArticleViewServiceImpl implements ArticleViewService {

    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult updateArticleViewCount(Integer articleId) {


        String uuid = UUID.randomUUID().toString();

        while (true){

            if (redisCache.setCacheObjectIfAbsent(SystemConstance.REDIS_ARTICLE_LOCK_KEY,
                    uuid,
                    SystemConstance.REDIS_LOCK_TIME_OUT,
                    SystemConstance.REDIS_TIMEUNIT))
            {
                redisCache.incrementByCacheHash(SystemConstance.REDIS_ARTICLE_VIEW_COUNT_KEY,articleId.toString(),SystemConstance.VIEW_INCREMENT);

                String script = "if redis.call('GET',KEYS[1]) == ARGV[1] " +
                                "then return redis.call('DEL',KEYS[1]) " +
                                "else return 0 end";

                DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                redisScript.setResultType(Long.class);
                redisScript.setScriptText(script);

                redisCache.execute(redisScript, Arrays.asList(SystemConstance.REDIS_ARTICLE_LOCK_KEY),uuid);

                break;
            }else {
                try {
                    Thread.sleep(SystemConstance.REDIS_LOCK_SLEEP_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }


        return ResponseResult.ok();
    }
}
